using System.Web.Http;
using System.Web.Http.Cors;
using JtwTestWebApi;
using JtwTestWebApi;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Todo.Entity.FormEnrity;
using Todo.Entity.ResponseEntity;

namespace Todo;

[ApiController]
[Microsoft.AspNetCore.Mvc.Route("[controller]/[action]")]
[EnableCors("*","*","*")]
public class UserController : ControllerBase
{
    private readonly JwtHelper _jwtHelper;
    private readonly IUser _userService;

    public UserController(IUser userService,JwtHelper jwtHelper)
    {
        _jwtHelper = jwtHelper;
        _userService = userService;
    }
    
    [Microsoft.AspNetCore.Mvc.HttpPost]
    public ResponseObject<UserData> Login([Microsoft.AspNetCore.Mvc.FromBody]UserForm userForm)
    {
        var user = _userService.Login(userForm.Username, PasswordMd5.md5(userForm.Password));
        if (user != null)
        {
            var jwtUserModel = new JwtUserModel() { UserId = user.Id , UserType = "user"};
            var token = _jwtHelper.GetJwtToken(jwtUserModel);
            var userData = new UserData { Id = user.Id, Username = user.Username,Token = token };
            return new ResponseObject<UserData>().OK(userData,"登录成功,欢迎回来!");
        }
        return new ResponseObject<UserData> ().Fail( null,"登录失败,请检查用户名或密码!");
    }

    [Microsoft.AspNetCore.Mvc.HttpPost]
    public ResponseObject<Object> Register([Microsoft.AspNetCore.Mvc.FromBody]UserForm userForm)
    {
        var user = _userService.Register(userForm.Username, PasswordMd5.md5(userForm.Password));
        if (user)
        {
            return new ResponseObject<Object>().OK(1, "注册成功!");
        }
        return new ResponseObject<Object>().Fail(null, "注册失败,请检查用户名是否已存在!");
    }

    [Microsoft.AspNetCore.Mvc.HttpPost]
    public ResponseObject<Object> Logout(Guid id)
    {
            return new ResponseObject<Object>().OK(1, "注销成功!");
        // return new ResponseObject<Object>().Fail(null, "注销失败,请检查token!");
    }
    
    [Microsoft.AspNetCore.Mvc.HttpPost]
    public ResponseObject<Object> VerifyToken(string token)
    {
        return new ResponseObject<Object>().OK(1, "Token正在有效期!");
        // return new ResponseObject<Object>().Fail(null, "Token已过期!");
    }
    
    // [Microsoft.AspNetCore.Mvc.HttpGet]
    // public IHttpActionResult Test()
    // {
    //     return Json()
    // }
}